package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.bugtags.library.Bugtags;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

public class ProblemBackFragment extends Fragment implements OnClickListener {
  //private static final int REQUEST_ALBUM = 0;
  private static final int REQUEST_RP1 = 1;
  private static final int REQUEST_RP2 = 2;
  private static final int REQUEST_RP3 = 3;
  private static final int REQUEST_RP4 = 4;
  protected String selcurFile = "";//文件上传服务器返回路径
  protected String mFilePath1 = "";//文件本地路径
  protected String mFilePath2 = "";//文件本地路径
  protected String mFilePath3 = "";//文件本地路径
  protected String mFilePath4 = "";//文件本地路径
  private BaseVolleyActivity mActivity;
  private EditText etfunctionModule;
  private EditText mEtproblemMessage;
  private EditText mEtRemark;
  private String mId;
  private TextView mTvRp1;
  private TextView mTvRp2;
  private TextView mTvRp3;
  private TextView mTvRp4;
  //private String mfileName;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();

    //CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.problem);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }

    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityIntent(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 提交反馈意见
      case R.id.menu_item_confirm:
        String functionModel = etfunctionModule.getText().toString().trim();
        if (!TextUtils.isEmpty(functionModel)) {
          if (functionModel.equalsIgnoreCase("#.op")) {
            SharedPreferencesUtil.setInt(getActivity(), SharedPreferencesUtil.BUGTAGS_OPTIONS,
                Bugtags.BTGInvocationEventShake);
            Bugtags.setInvocationEvent(Bugtags.BTGInvocationEventShake);
            ToastUtil.show("您已开启测试人员选项(摇一摇)");
            return true;
          }
          if (functionModel.equalsIgnoreCase("#.ed")) {
            SharedPreferencesUtil.setInt(getActivity(), SharedPreferencesUtil.BUGTAGS_OPTIONS,
                Bugtags.BTGInvocationEventNone);
            Bugtags.setInvocationEvent(Bugtags.BTGInvocationEventNone);
            ToastUtil.show("您已关闭测试人员选项");
            return true;
          }
          if (functionModel.equalsIgnoreCase("#.xfq")) {
            SharedPreferencesUtil.setInt(getActivity(), SharedPreferencesUtil.BUGTAGS_OPTIONS,
                Bugtags.BTGInvocationEventBubble);
            Bugtags.setInvocationEvent(Bugtags.BTGInvocationEventBubble);
            ToastUtil.show("您已开启测试人员选项(悬浮球)");
            return true;
          }
        }
        if (TextUtils.isEmpty(mEtproblemMessage.getText().toString())) {
          Toast.makeText(getActivity(), R.string.toastMessage, Toast.LENGTH_SHORT).show();
        } else {
          mId = UUID.randomUUID().toString();
          VolleySave();
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_problem_back, container, false);
    etfunctionModule = (EditText) v.findViewById(R.id.et_function_module);
    mEtproblemMessage = (EditText) v.findViewById(R.id.et_problem_message);
    mEtRemark = (EditText) v.findViewById(R.id.et_remark);
    //ImageView mIvPhotoProblem = (ImageView) v.findViewById(R.id.iv_photo_problem);
    mTvRp1 = (TextView) v.findViewById(R.id.tv_rp1);
    ImageView mIvExtra1 = (ImageView) v.findViewById(R.id.iv_extra1);
    mTvRp2 = (TextView) v.findViewById(R.id.tv_rp2);
    ImageView mIvExtra2 = (ImageView) v.findViewById(R.id.iv_extra2);
    mTvRp3 = (TextView) v.findViewById(R.id.tv_rp3);
    ImageView mIvExtra3 = (ImageView) v.findViewById(R.id.iv_extra3);
    mTvRp4 = (TextView) v.findViewById(R.id.tv_rp4);
    ImageView mIvExtra4 = (ImageView) v.findViewById(R.id.iv_extra4);

    mIvExtra1.setOnClickListener(this);
    mIvExtra2.setOnClickListener(this);
    mIvExtra3.setOnClickListener(this);
    mIvExtra4.setOnClickListener(this);

    //ImageButton mIbPhotoProblem = (ImageButton) v.findViewById(R.id.ib_photo_problem);
    //        mIbPhotoProblem.setOnClickListener(new OnClickListener() {
    //            @Override
    //            public void onClick(View arg0) {
    //                // 调用图库
    //                Intent intent = new Intent(Intent.ACTION_PICK, null);
    //                intent.setDataAndType(
    //                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    //                startActivityForResult(intent, REQUEST_ALBUM);
    //
    //            }
    //        });
    return v;
  }

  // 提交反馈意见
  private void VolleySave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_BACK_SUB);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("dataStatus", "new");
    String feedBack = mEtproblemMessage.getText().toString();
    String model = etfunctionModule.getText().toString();
    params.put("feedback", feedBack);
    if (!TextUtils.isEmpty(model)) {
      params.put("resname", model);
    }
    params.put("remark", mEtRemark.getText().toString());

    CurrentUser user = CurrentUser.newInstance(mActivity);
    Bugtags.sendFeedback(
        MyStringUtil.connect(user.getName(), getString(R.string.comma), user.getPassword(),
            params.toString()));
    LogUtil.i(params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          // 上传图片
          //                    if (!TextUtils.isEmpty(path)) {
          //                        upLoad();//自定义上传图片
          //                    }
          if (!TextUtils.isEmpty(mFilePath1)) {
            upLoad(mFilePath1, true, "resourcePath1");
          }
          if (!TextUtils.isEmpty(mFilePath2)) {
            upLoad(mFilePath2, true, "resourcePath2");
          }
          if (!TextUtils.isEmpty(mFilePath3)) {
            upLoad(mFilePath3, false, "resourcePath3");
          }
          if (!TextUtils.isEmpty(mFilePath4)) {
            upLoad(mFilePath4, false, "resourcePath4");
          }
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  protected void upLoad(String path, boolean isPicture, String resourcePath) {

    //        new FileNetWorkUtil(getActivity())
    //                .upLoadFile(path, ApiConst.URL_UPLOAD_FILE, null, "app", "sys_error_feedback", mId, null, true);

    new FileNetWorkUtil(getActivity()).upLoadFilePath(path, ApiConst.URL_UPLOAD_FILE, null, "app",
        "bpmx.sys_error_feedback", mId, null, isPicture, resourcePath);
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      //图片一
      case R.id.iv_extra1:
        choosePicture(REQUEST_RP1);
        break;
      //图片二
      case R.id.iv_extra2:
        choosePicture(REQUEST_RP2);
        break;
      //其他一
      case R.id.iv_extra3:
        chooseFile(REQUEST_RP3);
        break;
      //其他二
      case R.id.iv_extra4:
        chooseFile(REQUEST_RP4);
        break;
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private void choosePicture(int requestCode) {
    // 调用图库
    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(intent, requestCode);
  }

  //private void showDialog(int requestCode) {
  //    DialogFragment dialog = ExtraUpLoadDialogFragment.newInstance(mFilePath1, ExtraUpLoadDialogFragment.TYPE_PHOTO);
  //    FragmentManager fm = getActivity().getSupportFragmentManager();
  //    dialog.setTargetFragment(ProblemBackFragment.this, requestCode);
  //    dialog.show(fm, "");
  //}

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //        if (requestCode == REQUEST_ALBUM) {
    //            Uri uri = data.getData();
    //            path = FileUtil.getPath(getActivity(), uri);
    //            LogUtil.i("oldpath=" + path);
    //            Bitmap bm = BitmapFactory.decodeFile(path);
    //            if (bm == null) {
    //                Toast.makeText(getActivity(), "bitmap==null",
    //                        Toast.LENGTH_SHORT).show();
    //                return;
    //            }
    //            Bitmap mNewBitmap = ImageTools.zoomBitmap(bm, 400, 400);// 压缩图片
    //            bm.recycle();
    //
    //            mIvPhotoProblem.setImageBitmap(mNewBitmap);
    //            mIvPhotoProblem.setVisibility(View.VISIBLE);
    //            // 将压缩的图片重新保存
    //            File file = ImageTools.savePhotoToSDCard(mNewBitmap,
    //                    FileUtil.getFileDir(), System.currentTimeMillis() + "");
    //            path = file.getAbsolutePath();
    //            LogUtil.i("newpath=" + path);
    //        }

    if (requestCode == REQUEST_RP1) {
      mFilePath1 = getPicture(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath1);
      mTvRp1.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP2) {
      mFilePath2 = getPicture(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath2);
      mTvRp2.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP3) {
      mFilePath3 = getFile(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath3);
      mTvRp3.setText(mChoseFileName);
    }
    if (requestCode == REQUEST_RP4) {
      mFilePath4 = getFile(data);
      String mChoseFileName = FileUtil.getFileNameByFilePath(mFilePath4);
      mTvRp4.setText(mChoseFileName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private String getPicture(Intent data) {
    Uri uri = data.getData();
    String path = FileUtil.getPath(getActivity(), uri);
    Bitmap bm = BitmapFactory.decodeFile(path);
    if (bm == null) {
      Toast.makeText(getActivity(), "bitmap==null", Toast.LENGTH_SHORT).show();
      return "";
    }
    Bitmap mNewBitmap = ImageTools.zoomBitmap(bm, 400, 400);// 压缩图片
    bm.recycle();
    // 将压缩的图片重新保存
    File file = ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
        System.currentTimeMillis() + "");
    if (file != null) {
      return file.getAbsolutePath();
    }
    return "";
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }
}
